package com.example.demo.service;

import com.example.demo.dao.mapper.UserMapper;
import com.example.demo.dao.pojo.UserInfo;
import com.example.demo.vo.AdminUserVo;
import com.example.demo.vo.ErrorCode;
import com.example.demo.vo.LoginUserVo;
import com.example.demo.vo.Result;
import com.example.demo.vo.params.SearchParams;
import com.example.demo.vo.params.UpdateUserParams;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TokenService tokenService;

    private static final String slat = "t4dmw!@#";


    // 注册新用户
    public int add(String username, String password){
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        return userMapper.add(userInfo);
    }

    // 删除用户
    public int remove(String username){
        return userMapper.remove(username);
    }

    // 获取用户信息
    public UserInfo findUserByName(String username){
        return userMapper.selectOneByName(username);
    }

    // 查找用户
    public UserInfo findUser(String username, String password){
        return userMapper.select(username, password);
    }

    // 根据 token 查询用户信息
    public Result findUserByToken(String token){
        /**
         * 1. token 的合法性校验
         *    是否为空、解析是否成功、redis 是否存在
         * 2. 如果校验失败，返回错误
         * 3. 如果校验失败，返回结果
         */
        UserInfo userInfo = tokenService.checkToken(token);
        if(userInfo == null){
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(userInfo.getId());
        loginUserVo.setUsername(userInfo.getUsername());
        return Result.success(loginUserVo);
    }

    public Result userSearch(SearchParams params) {
        Integer page = params.getPage();
        Integer pageSize = params.getPageSize();
        String question = params.getQuestion();
        String token = params.getToken();
        int count = getCount("");
        if(question == null){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        List<UserInfo> userInfoList = userMapper.selectByLike("", (page-1)*pageSize, pageSize);
        if(userInfoList == null){
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        AdminUserVo adminUserVo = new AdminUserVo();
        adminUserVo.setUserInfoList(userInfoList);
        adminUserVo.setCount(count);
        return Result.success(adminUserVo);

    }

    public int getCount(String question) {
        return userMapper.getCount(question);
    }

    public Result deleteUser(int id) {
        int res = userMapper.deleteById(id);
        if(res == 1){
            return Result.success(null);
        }
        return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
    }

    public Result updateUser(UpdateUserParams params) {
        int id = params.getId();
        String username = params.getUsername();
        String password = params.getPassword();
        int admin = params.getAdmin();
        int result = 0;
        if(id == 0){
            if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
                return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
            }
            // 查找用户
            UserInfo userInfo = findUserByName(username);
            if(userInfo != null){
                return Result.fail(ErrorCode.ACCOUNT_EXIST.getCode(), ErrorCode.ACCOUNT_EXIST.getMsg());
            }
            // 将用户存到数据库
            password = DigestUtils.md5Hex(password + slat);
            UserInfo user = new UserInfo();
            user.setUsername(username);
            user.setPassword(password);
            user.setAdmin(admin);
            result = userMapper.add(user);
        }else if(userMapper.selectById(id) != null){
            result = userMapper.update(params);
        }
        if(result == 1){
            return Result.success(null);
        }
        return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
    }
}
